package com.sky.controller.user;

import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user/user")
@Slf4j
@Api(tags = "C端接口")
public class UserController {

//    注入服务接口
    @Autowired
    UserService userService;
    @Autowired // 这里直接用的原因是配置了yml文件，里面的属性都进行了注入
    JwtProperties jwtProperties;

    /**
     * C端用户登录接口
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("登录")
    public Result<UserLoginVO> wxLogin(@RequestBody UserLoginDTO userLoginDTO){
        log.info("微信登录id：{}",userLoginDTO.getCode());
//        微信登录对应的操作逻辑
        User user = userService.wxLogin(userLoginDTO);

//        获取到对象，生成JWT令牌
        Map<String, Object> claims = new HashMap<>();
//        获取用户对应数据库id
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
//        创建JWT令牌
        String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        log.info("用户端的jwt：{}",jwt);
//        构建返回前端的对象数据
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(jwt)
                .build();
        return Result.success(userLoginVO);
    }

    @PostMapping("/logout")
    @ApiOperation("退出")
    public Result<String> logout() {
        log.info("退出登录中...");
        return Result.success();
    }
}
